package com.sefer.dragonfly.client.utils;

import static com.sefer.dragonfly.client.constants.Constants.MBEAN_OBJECT_NAME_MONITOR;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class CommonUtils {

	/**
	 * 获取IP
	 * 
	 * @return
	 */
	public static String getIpAddr() {
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			StringBuilder addresses = new StringBuilder(1);

			int i = 0;
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces
						.nextElement();
				Enumeration<InetAddress> inetAddresses = networkInterface
						.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {

					InetAddress inetAddress = inetAddresses.nextElement();
					String hostAddress = inetAddress.getHostAddress();
					if (hostAddress.equals("127.0.0.1")) {
						continue;
					}
					if (i != 0) {
						addresses.append(",");
					}
					addresses.append(hostAddress);
					i++;
				}
			}
			return addresses.toString();
		} catch (SocketException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static String getStrObjectName(
			@SuppressWarnings("rawtypes") Class clazz) {
		if (clazz == null) {
			return null;
		}
		return MBEAN_OBJECT_NAME_MONITOR
				+ ClassUtils.getShortClassName(clazz.getName());
	}

	public static String getStrObjectName(
			@SuppressWarnings("rawtypes") String strObjectName) {
		if (StringUtils.isBlank(strObjectName)) {
			return null;
		}
		return MBEAN_OBJECT_NAME_MONITOR + strObjectName;
	}

	/**
	 * 打印对象的属性值
	 * 
	 * @param obj
	 * @return
	 */
	public static String beanToString(Object obj) {
		if (obj == null) {
			return "";
		}
		return ToStringBuilder.reflectionToString(obj,
				ToStringStyle.DEFAULT_STYLE);
	}

	public static void main(String[] args) {
		System.out.println(CommonUtils.getIpAddr());
	}

}
